const request = require('request');
const OSS 	  = require('ali-oss').Wrapper;
const co      = require("co");

exports.uploadOssFile = function(req,res) {
	
	//获取restful参数
    var restfulParams = req.routeInfo.restfulParams;
    
    //保存access_token
    var accessToken = "";
    
    //保存阿里云OSS临时TST
    var tstData = {};
    
    //最终结果
    var resultData = {};
	
	//任务流创建
    async.waterfall([
    	
    	//获取微信accessToken
    	function(cb){
    		
    		R.SEND_HTTP(
                req,
                {
//                  url    : config.publicConfig.MIDDLE_API_SERVER + "weixin/getAccessToken",
                    url    : "http://"+config.publicConfig.SERVER_IP+":3400/weixin/getAccessToken",
//                  url    : "http://demo2.artmofang.com:3400/weixin/getAccessToken",
                    method : 'GET'
                },
                function (err, data) {

                    if(err){
                        return RES.response(res,false,"公众号config配置签名获取失败");
                    }


                    accessToken = data.access_token;
                    //console.log("access_token:" + accessToken);
                    
                    cb();
            
                }
            );
    		
    	},
    	
    	//获取阿里云TST
    	function(cb){
    		
    		R.SEND_HTTP(
                req,
                {
                    url    : "http://127.0.0.1:3400/common/getTSTToken",
                    method : 'POST'
                },
                function (err, data) {

                    if(err){
                        return RES.response(res,false,"阿里云OSS令牌获取失败");
                    }

					tstData = data;
                    //console.log(data);
                    
                    cb();
                    
            
                }
            );
    		
    		
    	},
    	
    	
    	//进行OSS上传操作
    	function(cb){
    		
      		const ossClient = new OSS({
			  accessKeyId     : tstData.AccessKeyId,
			  accessKeySecret : tstData.AccessKeySecret,
			  bucket   : 'testfileupload',
			  stsToken :tstData.SecurityToken,
			  region   : 'oss-cn-beijing'
			});
			
			var newFileName = common.nowTime(false) + "-" + common.getRandom(5) + ".jpg";
			
			
			var mediaId     = restfulParams.mediaId;  // 微信多媒体文件id
			var destPath    = newFileName; 		  	  // OSS文件路径
			const wxReq     = request('http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' + accessToken + '&media_id=' + mediaId);
	
      		wxReq.on('response', (response) => {
				// request的响应结果response可以作为读取流传给ossClient
				co(function* () {
				    const result = yield ossClient.putStream(destPath, response, {timeout: 30 * 60 * 1000});
				    resultData.filename = result.name;
				    resultData.fileUrl  = result.url;
				    cb();
				}).catch(err => {
					//console.log(err)
				    return RES.response(res, false,"文件上传失败");
				});
    	});
    		
    	}
    	
    ],function(err, result){
        
       //返回最终拼接结果
       RES.response(res,true,resultData);
    
    });

	
}